<template>
  <div>
    <Card class="warp-card" dis-hover>
      <vxe-grid
        ref="vGrid"
        resizable
        border
        show-overflow
        highlight-hover-row
        row-id="id"
        :loading="loading"
        :form-config="tableForm"
        :toolbar="tableToolbar"
        :columns="tableColumn"
        pager-config
        :sort-config="sortConfig"
        :proxy-config="proxyConfig"
        @toolbar-button-click="buttonClick"
        show-footer
        :footer-method="footerMethod"
      ></vxe-grid>
    </Card>

    <SaleOrderTableAdd ref="SaleOrderTableAdd" @addSuccess="$refs.vGrid.commitProxy('reload')"></SaleOrderTableAdd>
  </div>
</template>

<script>
import { saleOrderApi } from "@/api/order/sale-order";
import SaleOrderTableAdd from "./components/sale-order-table-add";
export default {
  name: "SaleOrderList",
  components: {
    SaleOrderTableAdd
  },
  props: {},
  data() {
    return {
      loading: false,
      // 按钮权限设置
      buttonsPrivles: {},
      // column
      tableColumn: [
        {
          type: "seq",
          width: "50"
        },
        {
          title: "下单日期",
          field: "name"
        },
        {
          title: "订单编号",
          field: "specification"
        },
        {
          title: "客户名称",
          field: "specNo"
        },
        {
          title: "下单数量",
          field: "tags"
          //   formatter: this.formatterTags
        },
        {
          title: "毛利",
          field: "purchasePrice",
          sortable: true
        },
        {
          title: "金额",
          field: "purchasePrice"
        },
        {
          title: "利润率",
          field: "purchasePrice"
        },
        {
          title: "付款条件",
          field: "purchasePrice"
        },
        {
          title: "操作",
          field: "action",
          width: 160,
          align: "center",
          className: "action-hide",
          slots: {
            default: ({ row }, h) => {
              return this.$tableAction(h, [
                {
                  title: "详情",
                  action: () => {
                    this.getDetail(row);
                  }
                },
                {
                  title: "编辑",
                  directives: [
                    {
                      name: "privilege",
                      value: "sale-order-update"
                    }
                  ],
                  action: () => {
                    this.editEvent(row);
                  }
                },
                {
                  title: "删除",
                  directives: [
                    {
                      name: "privilege",
                      value: "sale-order-delete"
                    }
                  ],
                  action: () => {
                    this.deleteEvent(row);
                  }
                }
              ]);
            }
          }
        }
      ],
      // search form
      tableForm: {
        titleWidth: 100,
        titleAlign: "right",
        data: {
          searchCount: true,
          name: "",
          shortName: "",
          telephone: "",
          mnemonicCode: ""
        },
        items: [
          {
            field: "name",
            title: "产品名称",
            span: 6,
            titlePrefix: { message: "", icon: "fa fa-exclamation-circle" },
            itemRender: { name: "$input", props: { placeholder: "请输入名称" } }
          },
          {
            field: "specification",
            title: "规格",
            span: 6,
            itemRender: { name: "$input", props: { placeholder: "请输入简称" } }
          },
          {
            field: "spcNo",
            title: "规格书编号",
            span: 6,
            itemRender: {
              name: "$input",
              props: { placeholder: "请输入座机号" }
            }
          },
          {
            field: "tags",
            title: "标签",
            span: 6,
            folding: false,
            titleSuffix: {
              message: "注意，必填信息！",
              icon: "fa fa-info-circle"
            },
            itemRender: {
              name: "$input",
              props: { placeholder: "请输入助记码" }
            }
          },
          {
            span: 24,
            align: "center",
            collapseNode: false,
            itemRender: {
              name: "$buttons",
              children: [
                {
                  props: { type: "submit", content: "查询", status: "primary" }
                },
                { props: { type: "reset", content: "重置" } }
              ]
            }
          }
        ]
      },
      // 按钮
      tableToolbar: {
        id: "sale-order-list-button",
        refresh: true,
        export: true,
        custom: true,
        buttons: [
          {
            code: "insert_code",
            name: "新增",
            icon: "fa fa-plus",
            visible: true
          }
        ]
      },
      //sortConfig
      sortConfig: {
        remote: true,
        trigger: "cell"
      },
      //proxyConfig
      proxyConfig: {
        seq: true,
        sort: true,
        form: true,
        props: {
          result: "data.list",
          total: "data.total"
        },
        ajax: {
          query: this.findList
        }
      }
    };
  },
  computed: {},
  watch: {},
  filters: {},
  created() {},
  methods: {
    // 获取数据列表
    findList({ page, sort, form }) {
      // 处理排序条件
      let queryParams = Object.assign(
        {
          pageNum: page.currentPage,
          pageSize: page.pageSize
        },
        form
      );
      if (sort.field !== undefined) {
        queryParams = Object.assign(
          {
            sort: sort.order === "asc",
            orderByField: sort.field
          },
          queryParams
        );
      }
      return saleOrderApi.getList(queryParams);
    },
    // 新增
    insertEvent() {
      this.$refs["SaleOrderTableAdd"].showModal();
    },
    editEvent(row) {
      saleOrderApi
        .getDetail(row.id)
        .then(response => {
          this.$refs["SaleOrderTableAdd"].showModal(response.data);
        })
        .catch(error => {});
    },
    formatterTags({ cellValue }) {
      const item = this.$refs.SaleOrderTableAdd.tagList.find(
        item => item.value === cellValue
      );
      return item ? item.label : "";
    },
    // 删除确定
    async deleteSure(delId) {
      this.loading = true;
      let res = await saleOrderApi.delete(delId);
      this.$Message.success("删除成功");
      this.loading = false;
      this.$refs.vGrid.commitProxy("reload");
      // this.findList();
    },
    // 删除操作
    deleteEvent(row) {
      this.$Modal.confirm({
        title: "友情提醒",
        content: "确定要删除吗？",
        onOk: () => {
          this.deleteSure(row.id);
        }
      });
    },
    // 详情
    async getDetail(row) {
      this.loading = true;
      let res = await saleOrderApi.getDetail(row.id);
      this.loading = false;
      this.$refs["SaleOrderTableAdd"].showModal(res.data, true);
    },
    buttonClick({ code }, event) {
      switch (code) {
        case "insert_code":
          this.insertEvent();
      }
    },
    exportMethod({ options }) {
      const proxyInfo = this.$refs.xGrid.getProxyInfo();
      const body = {
        filename: options.filename,
        sheetName: options.sheetName,
        isHeader: options.isHeader,
        original: options.original,
        mode: options.mode,
        pager: proxyInfo.pager,
        ids:
          options.mode === "selected" ? options.data.map(item => item.id) : [],
        fields: options.columns.map(column => {
          return {
            field: column.property,
            title: column.title
          };
        })
      };
      // 开始服务端导出
      return XEAjax.post(
        "https://api.xuliangzhan.com:10443/api/user/export",
        body
      )
        .then(data => {
          if (data.id) {
            this.$XModal.message({
              message: "导出成功，开始下载",
              status: "success"
            });
            // 读取路径，开始下载
            location.href = `https://api.xuliangzhan.com:10443/api/download/${data.id}`;
          }
        })
        .catch(() => {
          this.$XModal.message({ message: "导出失败！", status: "error" });
        });
    },
    footerMethod({ columns, data }) {
      const means = [];
      const sums = [];
      const others = [];
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          means.push("平均");
          sums.push("和值");
          others.push("其他");
        } else {
          let meanCell = null;
          let sumCell = null;
          let otherCell = "-";
          switch (column.property) {
            case "age":
            case "rate":
              meanCell = parseInt(XEUtils.mean(data, column.property));
              sumCell = XEUtils.sum(data, column.property);
              break;
            case "sex":
              otherCell = "无";
              break;
          }
          means.push(meanCell);
          sums.push(sumCell);
          others.push(otherCell);
        }
      });
      // 返回一个二维数组的表尾合计
      return [means, sums, others];
    }
  }
};
</script>
